/**
 * Created by zhangxiaoyu on 16/4/28.
 */
angular.module('hyt.menuCtrl',[])

    .controller('MenuListCtrl',function($scope,$rootScope,MenuListFactory,ENV,Storage,CheckAPKFactory,$ionicPopup,$ionicLoading,$timeout,$cordovaFileTransfer,$cordovaFileOpener2,$cordovaGPS){
        var sid=Storage.get('sid');
        var user_id=Storage.get('user_id');
        var yh_id=Storage.get('yh_id');
        var sfwlgs=Storage.get('sfwlgs');
        var dw_id=Storage.get('dw_id');
        var zd_id=Storage.get('zd_id');
        var sjh=Storage.get('lxdh');
        var version_no=ENV.version_no;
        var APIUrl =  Storage.get('fwqdz');
        var download_url;
        var confirmPopup;
        var content;
        $scope.dwmc=Storage.get('dwmc');
        $scope.dw_id=dw_id;
        Storage.set('tabBs',0);
        Storage.set('dzTab',0);
        Storage.set('fhd',null);
        Storage.set('buDan',null);
        if (Storage.get('menuDatas')!=null){
            $scope.menuDatas=Storage.get('menuDatas');
        }else {
            MenuListFactory.getMenuList(sid,user_id,yh_id,sfwlgs,dw_id);
        }
        $scope.$on('MenuList.menuUpdated', function() {
            $scope.menuDatas=MenuListFactory.getMenu();
            Storage.set("menuDatas",$scope.menuDatas);
            console.log($scope.menuDatas);
        });
        $timeout(function(){
            if($scope.menuDatas.nfdw==1){
                var permissions = cordova.plugins.permissions;
                permissions.hasPermission(permissions.ACCESS_COARSE_LOCATION, function( status ){
                  if ( status.hasPermission ) {
                    console.log("Yes :D ");
                  }
                  else {
                    permissions.requestPermission(permissions.ACCESS_COARSE_LOCATION, function( status ) {
                      if( !status.hasPermission ) error();
                    }, function() {
                      console.warn('ACCESS_COARSE_LOCATION permission is not turned on');
                    });
                  }
                });
                var option = {"yh_id":yh_id,"dw_id":dw_id,"sid":sid,"user_id":user_id,"api":APIUrl,"sjh":sjh};
                $cordovaGPS.startGPS(function(success){

                },function(error){

                },option);
            }
        },1000);
        MenuListFactory.queryContent1(sid,user_id,yh_id,dw_id);
        $scope.$on('UpdateContent1.APK',function(){
            var result=MenuListFactory.getResultContent1();
            if(result.ACTION_RETURN_CODE=='000000'){
                content=result.ACTION_INFO.RESULT_LIST[0].gxnr;
                Storage.set("content",content);
            }
        });
        if(Storage.get('isCheckApk')==false){
            MenuListFactory.checkApk(version_no,sid,user_id,yh_id,dw_id);
            Storage.set('isCheckApk',true);
        }

        $scope.$on('UpdateApk.APK',function(){
            var result=MenuListFactory.getResultApk();
            if(result.ACTION_INFO.TOTAL>0){
                download_url=result.ACTION_INFO.RESULT_LIST[0].download_url;
            }
            if(result.ACTION_RETURN_CODE=='000000'){
                if(result.ACTION_INFO.TOTAL>0){
                    showUpdateConfirm();
                }
            }
        });

        var networkState ;
        var states = {};
        document.addEventListener("deviceready", onDeviceReady, false);
        function onDeviceReady() {
            networkState=navigator.connection.type;
            states[Connection.UNKNOWN]  = 'Unknown connection';
            states[Connection.ETHERNET] = 'Ethernet connection';
            states[Connection.WIFI]     = 'WiFi connection';
            states[Connection.CELL_2G]  = 'Cell 2G connection';
            states[Connection.CELL_3G]  = 'Cell 3G connection';
            states[Connection.CELL_4G]  = 'Cell 4G connection';
            states[Connection.CELL]     = 'Cell generic connection';
            states[Connection.NONE]     = 'No network connection';
        }

        function showUpdateConfirm() {
            confirmPopup = $ionicPopup.confirm({
                title: '版本升级',
                template: Storage.get("content"), //从服务端获取更新的内容
                cancelText: '取消',
                okText: '升级'
            });
            confirmPopup.then(function (res) {
                if (res) {
                    if(states[networkState]=='No network connection'){
                        $ionicLoading.show({template: '无网络连接', noBackdrop: true, duration: 2000});
                    }else if(states[networkState]=='Cell 2G connection'||states[networkState]=='Cell 3G connection'||states[networkState]=='Cell 4G connection'||states[networkState]=='Cell generic connection'){
                        var pop= $ionicPopup.confirm({
                            template: '检测到您当前使用的是流量，是否要继续下载?',
                            cancelText: '取消',
                            okText: '继续'
                        });
                        pop.then(function(res){
                            $ionicLoading.show({
                                template: "已经下载：0%"
                            });
                            var url = download_url; //可以从服务端获取更新APP的路径
                            var targetPath= "file:///storage/sdcard0/hytAndroid/hyt.apk";
                            //APP下载存放的路径，可以使用cordova file插件进行相关配置
                            var trustHosts = true;
                            var options = {};
                            $cordovaFileTransfer.download(url,targetPath,options,trustHosts).then(function (result) {
                                // 打开下载下来的APP
                                $cordovaFileOpener2.open(targetPath, 'application/vnd.android.package-archive'
                                ).then(function () {
                                    // 成功
                                }, function (err) {
                                    // 错误
                                });
                                $ionicLoading.hide();
                            }, function (err) {
                                $ionicLoading.show({template: '下载失败！', noBackdrop: true, duration: 2000});
                            }, function (progress) {
                                //进度，这里使用文字显示下载百分比
                                $timeout(function () {
                                    var downloadProgress = (progress.loaded / progress.total) * 100;
                                    $ionicLoading.show({
                                        template: "已经下载：" + Math.floor(downloadProgress) + "%"
                                    });
                                    if (downloadProgress > 99) {
                                        $ionicLoading.hide();
                                    }
                                })
                            });
                        })
                    }
                    else{
                        $ionicLoading.show({
                            template: "已经下载：0%"
                        });
                        var url = download_url; //可以从服务端获取更新APP的路径
                        var targetPath= "file:///storage/sdcard0/hytAndroid/hyt.apk";
                        //APP下载存放的路径，可以使用cordova file插件进行相关配置
                        var trustHosts = true;
                        var options = {};

                        $cordovaFileTransfer.download(url,targetPath,options,trustHosts).then(function (result) {
                            // 打开下载下来的APP
                            $cordovaFileOpener2.open(targetPath, 'application/vnd.android.package-archive'
                            ).then(function () {
                                // 成功
                            }, function (err) {
                                // 错误
                            });
                            $ionicLoading.hide();
                        }, function (err) {
                            $ionicLoading.show({template: '下载失败！', noBackdrop: true, duration: 2000});
                        }, function (progress) {
                            //进度，这里使用文字显示下载百分比
                            $timeout(function () {
                                var downloadProgress = (progress.loaded / progress.total) * 100;
                                $ionicLoading.show({
                                    template: "已经下载：" + Math.floor(downloadProgress) + "%"
                                });
                                if (downloadProgress > 99) {
                                    $ionicLoading.hide();
                                }
                            })
                        });
                    }
                } else {
                    // 取消更新
                }
            });
        }
    });
